'use strict';

const { Controller } = require('egg');
const moment = require('moment');
const utility = require('utility')

class UserController extends Controller {
  async login() {
    const { ctx,app } = this;
    const { username,password} = ctx.request.body;
    const h_password = utility.md5(password);
    const user = await ctx.model.User.findOne({
      where:{
        h_username:username,
        h_password:h_password
      }
    })
    if(user){
      const token = app.jwt.sign({
        name: user.h_username,
      }, app.config.jwt.secret);
      ctx.body = {
        code: "1",
        message: '登录成功',
        data: { id: user.id,username:user.h_username,nickname:user.h_nickname},
        token
      };
    }else{
      ctx.body ={
        code:"0",
        msg:"用户名或密码错误"
      }
    }
    
  }

  async reg() {
    const { ctx } = this;
    const { h_nickname,h_username,password} = ctx.request.body;
    const h_password = utility.md5(password);
    console.log(h_password,'h_password')
    const create_time = moment().format("YYYY-MM-DD HH:mm");
    const update_time = moment().format("YYYY-MM-DD HH:mm");
    const user = await ctx.model.User.create({h_nickname,h_username,h_password,create_time,update_time});
    ctx.status = 201;
    ctx.body = user;
  }
}

module.exports = UserController;